//
//  TimLine.m
//  TwitterClient3
//
//  Created by goccy on 11/10/29.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "TimeLine.h"
#import "ConnectionHandler.h"
#import "JSON.h"

@implementation TimeLine


#pragma mark -
#pragma mark Initialization


- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    self = [super initWithStyle:style];
    if (self) {
		//GET ACCESS to TWITTER_SERVER
		tweetID = 0;
		isInitializeTime = true;
		tweetData = [[NSMutableArray alloc] init];
		userNameData = [[NSMutableArray alloc] init];
		userImageData = [[NSMutableArray alloc] init];
		[self requestTakeTimeline];
		NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:5
					     target: self selector:@selector(timerEvent) userInfo:nil repeats:YES];
    }
    return self;
}

-(void)requestTakeTimeline
{
	char request_url[128] = {0};
	snprintf(request_url, 128, "http://%s/cgi-bin/twitter/timeline.json?tweet_id=%d", HOST_NAME, tweetID);
	fprintf(stderr, "request_url = [%s]\n", request_url);
	NSString* urlstr = [NSString stringWithCString: request_url encoding:NSUTF8StringEncoding];
	NSURL *url = [NSURL URLWithString:urlstr];
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
	[request setHTTPMethod:@"GET"];
	ConnectionHandler *handler = [[[ConnectionHandler alloc] init] autorelease];
	[handler setTimelineController:self];
	NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:handler];
}

-(NSMutableArray *)getTweetData
{
	return tweetData;
}

-(NSMutableArray *)getUserNameData
{
	return userNameData;
}

-(NSMutableArray *)getUserImageData
{
	return userImageData;
}

-(void)displayTimeline:(NSString *)response
{
	NSLog(@"=================startup==================\n [%@]", response);
	int most_recent_tweet_id = tweetID;
	if ([response isEqualToString:@""]) return;
	NSArray *statuses = [response JSONValue];
	if (!statuses) return;
	if (isInitializeTime) {
		for (NSDictionary *status in statuses) {
			//NSLog(@"text - %@", [status objectForKey:@"text"]);
			[tweetData addObject: [status objectForKey:@"text"]];
			[userNameData addObject:[status objectForKey:@"user_name"]];
			[userImageData addObject:[status objectForKey:@"image_src"]];
			int tweet_id = [[status objectForKey:@"tweet_id"] intValue];
			if (tweet_id > most_recent_tweet_id) {
				most_recent_tweet_id = tweet_id;
			}
			NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[tweetData count]-1 inSection:0];
			NSArray *indexPaths = [NSArray arrayWithObjects:indexPath,nil];
			//fprintf(stderr, "tweetData count = [%d]\n", [tweetData count]);
			[self.tableView beginUpdates];
			[self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
			[self.tableView endUpdates];
		}
		isInitializeTime = false;
	} else {
		int i = 0;
		for (NSDictionary *status in statuses) {
			[tweetData insertObject: [status objectForKey:@"text"] atIndex:i];
			[userNameData insertObject: [status objectForKey:@"user_name"] atIndex:i];
			[userImageData insertObject:[status objectForKey:@"image_src"] atIndex:i];
			int tweet_id = [[status objectForKey:@"tweet_id"] intValue];
			if (tweet_id > most_recent_tweet_id) {
				most_recent_tweet_id = tweet_id;
			}
			NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
			NSArray *indexPaths = [NSArray arrayWithObjects:indexPath,nil];
			//fprintf(stderr, "tweetData count = [%d]\n", [tweetData count]);
			[self.tableView beginUpdates];
			[self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
			[self.tableView endUpdates];
			i++;
		}
	}
	tweetID = most_recent_tweet_id;
	fprintf(stderr, "most_recent_tweet_id = [%d]\n", most_recent_tweet_id);
}

-(void)timerEvent
{
	[self requestTakeTimeline];
}

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
	//self.listOfContents;
	//[self addObject: @"1"];
	//[self addObject: @"2"];
	//[self addObject: @"3"];
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [tweetData count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 80.0f;
}

//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
//    return @"TimeLine";
//}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
	NSString *username = [userNameData objectAtIndex:indexPath.row];
	NSString *tweetdata = [tweetData objectAtIndex:indexPath.row];
	NSString *imagedata = [userImageData objectAtIndex:indexPath.row];
	NSLog(@"%@:%@:%@", username, tweetdata, imagedata);
	cell.textLabel.text = username;//[NSString stringWithFormat:@"%@\n%@", username, tweetdata];
	//NSLog(@"%@", cell.textLabel.font.familyName);
	UIFont *font = [UIFont fontWithName:@"Helvetica-Bold" size:16];
	UIFont *detailFont = [UIFont fontWithName:@"Helvetica" size:18];
	cell.textLabel.font = font;
	cell.detailTextLabel.text = tweetdata;
	cell.detailTextLabel.font = detailFont;
	cell.detailTextLabel.textColor = [UIColor blackColor];
	UIImage *image = NULL;
	if (imagedata) {
		char request_url[128] = {0};
		snprintf(request_url, 128, "http://%s/%s", HOST_NAME, [imagedata UTF8String]);
		NSString* urlstr = [NSString stringWithCString: request_url encoding:NSUTF8StringEncoding];
		NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlstr]];
		image = [[UIImage alloc] initWithData:data];
	} else {
		image = [UIImage imageNamed:@"twitter_icon.png"];
	}
	CGFloat width = 50;
	CGFloat height = 50;
	UIGraphicsBeginImageContext(CGSizeMake(width, height));
	[image drawInRect:CGRectMake(0, 0, width, height)];
	UIImage *resized_image = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext(); 
	cell.imageView.image = resized_image;
	cell.textLabel.textAlignment = UITextAlignmentCenter;
	cell.detailTextLabel.textAlignment = UITextAlignmentCenter;
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
    /*
     *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
    */
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[tweetData release];
    [super dealloc];
}


@end

